#include "mystdio.h"

MyFile* BuyFile(int fd, int flag)
{
    MyFile* f = (MyFile*)malloc(sizeof(MyFile));
    if(f == NULL) return NULL;
    f->fileno = fd;
    f->bufferlen = 0;
    f->flag = flag;
    f->flush_method = LINE_FLUSH;
    memset(f->buffer, 0, sizeof(f->buffer));
    return f;
}

MyFile* MyFopen(const char *path, const char *mode)
{
    int fd = -1;
    int flag = 0;
    if(strcmp(mode, "r") == 0)
    {
        flag = O_RDONLY;
        fd = open(path, flag);
    }
    else if(strcmp(mode, "w") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_TRUNC;
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode, "a") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_APPEND;
        fd = open(path, flag, 0666);
    }

    if(fd < 0) return NULL;
    return BuyFile(fd, flag);
}
void MyFclose(MyFile* f)
{
    if(f->fileno < 0) return;
    MyFlush(f);
    close(f->fileno);
    free(f);
}

int MyFwrite(MyFile* f, const void* str, int len)
{
    //拷贝
    memcpy(f->buffer + f->bufferlen, str, len);
    f->bufferlen += len;

    //判断是否需要刷新
    if((f->flush_method & LINE_FLUSH) && (f->buffer[f->bufferlen - 1] == '\n'))
    {
        MyFlush(f);
    }
    return 0;
}

void MyFlush(MyFile* f)
{
    write(f->fileno, f->buffer, f->bufferlen);
    fsync(f->fileno);
    f->bufferlen = 0;
}
